/*
 * @Author: nengwu 409791297@qq.com
 * @Date: 2020-06-30 18:03:13
 * @LastEditors: mylesshie@gmail.com
 * @LastEditTime: 2020-09-27 00:05:14
 * @description: 
 */
import axios from 'axios'
import { navigate } from '@/libs/rootNavigation'
import { Toast } from 'native-base'
import proxyConfig from '../proxy.config'
const apiHost = process.env === 'production' ? proxyConfig.production : proxyConfig.dev

function createFormData(data) {
  let formData = new FormData()
  formData.append('file', {
    uri: data.file,
    type: data.type,
    name: data.fileName || ('unname.' + data.type.replace('image/', '')) //ios中选择图片后无名字，无法上传
  })
  return formData
}

const fetch = async (options) => {

  let opts = Object.assign({
    method: 'POST'
  }, options)

  if (opts.form) {
    opts.data = createFormData(opts.data)
  }

  opts.params = opts.params || {}
  let timeStr = Date.now()
  opts.params.timeStr = timeStr
  let loginData = {}
  try {
    loginData = await global.storage.load({ key: 'loginState' })
  } catch (err) {
    loginData = {}
  }

  opts.headers = {
    platformType: 'ctApp',
    'AUTH-TOKEN': loginData.token ? loginData.token : '',
    user_id: loginData.uid ? loginData.uid : ''
  }
  // console.log('33333333333333')
  // console.log(loginData.token)
  // console.log('333333333333333')
  opts.url = apiHost + opts.url
  opts.timeout = 10000
  // let loading
  // if (!opts.hideLoading) {
  //   loading = Actions.loading()
  // }
  return new Promise((resolve, reject) => {
    console.log('request-start---------:【', opts.actionType, '】------>:', opts.url, opts)
    axios(opts).then(res => {
      if (res.status === 200) {
        console.log('request-success----------------:【', opts.actionType, '】------>:')
        if (res.data.code === 0) {
          resolve(res.data.data || {})
          // Actions.pop({refresh: {
          //   needRefresh: Math.random()
          // }})
        } else if (res.data.code === 100403) {
          navigate('Login')
          // 未登录
          console.log('----------------未登录，请重新登录-----------------')
          global.storage.save({
            key: 'loginState',
            data: {}
          })
        } else {
          // Actions.pop()
          res.data.message && Toast.show({
            text: res.data.message,
            duration: 1500
          })
          reject(res.data || {})
        }
      } else {
        reject(res)
      }
    }).catch(err => {
      console.log('axios------error:', err)
      reject(err)
    })
  })
}

export default fetch
